package com.yh.csx.crm.task;

import com.alibaba.dubbo.config.annotation.Reference;
import com.yh.b2b.common.constant.ResponseCode;
import com.yh.b2b.common.response.CommonResultResponse;
import com.yh.b2b.mall.facade.stub.customer.CustomerDataFacade;
import com.yh.b2b.mall.facade.stub.customer.req.CustomerOrderStatRes;
import com.yh.csx.crm.dao.ReportOrderStatMapper;
import com.yh.csx.crm.po.ReportOrderStat;
import com.yh.csx.crm.qo.SimpleCustomerQo;
import com.yh.csx.crm.vo.CustomerSimpleVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Huang Zhaoping
 * @date 2019/3/2
 */
@Slf4j
@Component
public class MallOrderSyncTask extends AbstractCustomerSyncTask {

    @Autowired
    private ReportOrderStatMapper orderStatMapper;

    @Reference
    private CustomerDataFacade customerDataFacade;

    @Scheduled(initialDelay = 60000, fixedDelay = 10000)
    public void syncOrderStat() {
        syncAllCustomer(SimpleCustomerQo.builder()
                .batchSize(10).hasCustomerNumber(true).build(), list -> {
            String[] sapCusCodes = list.stream().map(CustomerSimpleVo::getCustomerNumber).filter(StringUtils::isNotBlank).toArray(l -> new String[l]);
            if (sapCusCodes.length == 0) return;
            try {
                CommonResultResponse<List<CustomerOrderStatRes>> response = customerDataFacade.getMonthOrderStat(sapCusCodes, 30);
                if (response.getCode() != ResponseCode.SUCCESS) {
                    log.warn("查询客户订单统计数据失败：" + response.getMessage());
                    return;
                }
                List<CustomerOrderStatRes> result = response.getResult();
                Map<String, CustomerOrderStatRes> statMap = new HashMap<>();
                if (CollectionUtils.isNotEmpty(result)) {
                    for (CustomerOrderStatRes stat : result) {
                        statMap.put(stat.getSapCusCode(), stat);
                    }
                }
                List<ReportOrderStat> statList = list.stream().map(vo -> {
                    ReportOrderStat stat = new ReportOrderStat();
                    stat.setCustomerId(vo.getId());
                    stat.setCustomerName(vo.getCustomerName());
                    stat.setCustomerNumber(vo.getCustomerNumber());
                    CustomerOrderStatRes data = statMap.get(vo.getCustomerNumber());
                    stat.setStatDays(data == null ? 30 : data.getStatDays());
                    stat.setTotalAmount(data == null ? BigDecimal.ZERO : data.getTotalAmount());
                    stat.setOrderCount(data == null ? 0 : data.getOrderCount());
                    stat.setOrderDays(data == null ? 0 : data.getOrderDays());
                    stat.setLastOrderTime(data == null ? null : data.getLastOrderTime());
                    stat.setNoOrderDays(data == null ? 30 : data.getNoOrderDays());
                    stat.setDayAvgAmount(data == null || data.getOrderDays() == null || data.getOrderDays() == 0 ? BigDecimal.ZERO : data.getTotalAmount().divide(new BigDecimal(stat.getOrderDays()), 2, BigDecimal.ROUND_HALF_UP));
                    stat.setOrderAvgAmount(data == null || data.getOrderCount() <= 0 ? BigDecimal.ZERO : data.getTotalAmount().divide(new BigDecimal(stat.getOrderCount()), 2, BigDecimal.ROUND_HALF_UP));
                    stat.setUpdateTime(new Date());
                    return stat;
                }).collect(Collectors.toList());
                // 批量更新客户订单统计数据
                orderStatMapper.batchUpdateOrderStat(statList);
            } catch (Exception e) {
                log.error("同步客户订单数据异常：" + e.getMessage(), e);
            }
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
            }
        });

    }

    @Scheduled(cron = "0 0 0 * * ?")
    public void clearInvalidData(){
        orderStatMapper.clearInvalidData();
    }
}
